package com.sz.springboot_jpa.cntroller;

import com.mongodb.BasicDBObject;
import com.sz.springboot_jpa.entity.Book;
import com.sz.springboot_jpa.mongo.BookRepository;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * 2019/11/14
 */
@RestController
@RequestMapping("book")
public class BookController {

    @Resource
    private BookRepository cr;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private MongoOperations mongoOperations;


    @PostMapping
    public String post(@RequestBody Book book){
        cr.insert(book);
        return  "OK";
    }

    /**
     * 新增章节功能实现
     * @param book
     * @return
     */
    @PostMapping("addChapters")
    public String addChapters(@RequestBody Book book){
        Query query = new Query(Criteria.where("_id").is(book.getId()));
        Update update = new Update();
        update.push("chapters").each(book.getChapters());
        mongoTemplate.updateFirst(query,update,Book.class);
        return "ok";
    }
//  这种方式无法实现排序
//    @GetMapping("{id}")
//    public Book get(@PathVariable("id") String id){
//        return cr.findById(id).get();
//    }

    @GetMapping("{id}")
    public Book get(@PathVariable("id") String id){
//        TypedAggregation aggregation = new TypedAggregation();
        //先分解 后排序
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("_id").is(id)),
                Aggregation.unwind("chapters"),//拆解
                Aggregation.sort(Sort.by("chapters.order")));
        AggregationResults<BasicDBObject> book = mongoTemplate.aggregate(aggregation, Book.class, BasicDBObject.class);
        List<BasicDBObject> mappedResults = book.getMappedResults();
        System.out.println(mappedResults);
        return null;
    }

    @GetMapping
    @RequestMapping("getAll")
    public List<Book> getAll(){
        Query query = new Query();
        query.with(Sort.sort(Book.class).by("score").descending());
        List<Book> books = mongoTemplate.find(query, Book.class);
        return books;
    }
}
